package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.APIConstant;
import com.sky.exception.RequiredFillInException;
import com.sky.mapper.HistoryTodayMapper;
import com.sky.service.HistoryTodayService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.HistoryTodayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class HistoryTodayServiceImpl implements HistoryTodayService {

    @Autowired
    private HistoryTodayMapper historyTodayMapper;

    @Override
    public HistoryTodayVO getData(String date) {
        if(date == null || "".equals(date)){
            throw new RequiredFillInException("日期不能为空");
        }
        HistoryTodayVO historyTodayVO = historyTodayMapper.getHistoryData(date);

        //判断historyTodayVO是否为空，如果为空就请求远程api
        if(historyTodayVO == null){
            String json = HttpClientUtil.doGet(APIConstant.HISTORY_TODAY,null);
            JSONObject jsonObject = JSON.parseObject(json);
            String data = JSON.parseObject(jsonObject.getString("data")).getString("data");
            historyTodayVO = HistoryTodayVO.builder()
                    .data(data)
                    .date(date)
                    .build();
            historyTodayMapper.insert(historyTodayVO);
        }
        return historyTodayVO;
    }
}
